package com.xiyou.luckdraw.api.service.impl;

import com.xiyou.luckdraw.api.dal.entitys.SysUser;
import com.xiyou.luckdraw.api.dal.mapper.luckdraw.LoginMapper;
import com.xiyou.luckdraw.api.dal.mapper.luckdraw.SysUserMapper;
import com.xiyou.luckdraw.api.dto.login.*;
import com.xiyou.luckdraw.api.service.LoginService;
import com.xiyou.luckdraw.common.constants.ResultCodeConstants;
import com.xiyou.luckdraw.common.enums.SystemUserStatusEnum;
import com.xiyou.luckdraw.common.utils.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName: LoginServiceImpl
 * @Description:
 * @author: limingxing
 * @Date: 2019-10-15 20:32
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private LoginMapper loginMapper;
    @Autowired
    SysUserMapper sysUserMapper;

    @Override
    public UserInfoDto getUser(String userName) {
        log.error("Begin LoginServiceImpl.getUser userName: {}",userName);
        return loginMapper.getUser(userName);
    }

    @Override
    public List<UserRoleInfo> getRole(Long userId) {
        log.error("Begin LoginServiceImpl.getRole userId: {}",userId);
        return loginMapper.getRole(userId);
    }

    @Override
    public List<RolePermission> getPermission(Long userId) {
        log.error("Begin LoginServiceImpl.getPermission userId: {}",userId);
        return loginMapper.getPermission(userId);
    }

    @Override
    public UpdateSysUserResponse modifyPwd(UserModifyRequest param) {
        UpdateSysUserResponse response = new UpdateSysUserResponse();
        SysUser old = sysUserMapper.selectByPrimaryKey(param.getId());
        if (old == null || old.getStatus() == SystemUserStatusEnum.delete.getKey()) {
            response.setCode(-1);
            response.setMsg("账号已删除!");
            return response;
        }
        String oldPwd = MD5Utils.encode(param.getOldPassword(),old.getUserName());
        if (!old.getPassword().equals(oldPwd)){
            response.setCode(-1);
            response.setMsg("原密码错误!");
            return response;
        }
        SysUser modify = new SysUser();
        modify.setId(param.getId());
        modify.setPassword(MD5Utils.encode(param.getPassword(),old.getUserName()));
        modify.setUpdatorId(param.getId());
        modify.setUpdatorName(param.getName());
        int result = sysUserMapper.updateByPrimaryKeySelective(modify);
        response.setCode(ResultCodeConstants.SUCCESS.getCode());
        response.setMsg(ResultCodeConstants.SUCCESS.getMessage());
        return response;
    }
}
